import java.applet.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
import javax.swing.filechooser.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
import java.text.*;
/**
 * No copyright.
 * Class to provide a useful GUI to manage the functions of AdminTracker
 * @author Quan Nguyen
 * @version 1.08 2008-July-29
 */

public class AdminTrackerGUI extends JPanel implements ActionListener, ListSelectionListener, TextListener, WindowListener
{   
    private JMenuItem menuHelp;
    private JMenuItem menuAbout;
    private JMenuItem menuSave;

    private JList eventList;
    private JTextField[] eventFields;
    private ArrayList<Event> eventArr;
    private DefaultListModel eventModel = new DefaultListModel();
    private Event evtDisplay; //the event currently being manipulated
    private JComboBox epm;
    private DefaultComboBoxModel dcbmepm;
    private JCheckBox[] eventFMBoxes;
    private String[] fieldMeetLabels = {"ACX", "AX", "AR", "CG", "PT", "UX", "UR"};
    private String[] fieldMeetLongLabels = {"Academics", "Armed Exhibition", "Armed Regulation", "Color Guard", "PT", "Unarmed Exhibition", "Unarmed Regulation"};
    private JComboBox efmlist;
    
    private JList studentList;
    private JTextField[] studentFields;
    private ArrayList<Student> studentArr;
    private DefaultListModel studentModel = new DefaultListModel();
    private Student stuDisplay; //the student currently being manipuated
    
    private JScrollPane scrollPane;
    private AdminTrackerTableModel tableModel;
    private JTable table;
    private TextField tableSearch;
    
    private JComboBox ribbonList;
    private DefaultComboBoxModel ribbonModel;
    private String[] awardLevel = {"No award", "Ribbon", "Ribbon and 1 bronze star",
                                   "Ribbon and 2 bronze stars", "Ribbon and 1 silver star",
                                   "Ribbon and 2 silver stars", "Ribbon and 1 gold star",
                                   "Ribbon and 2 gold stars", "Ribbon and 3 gold stars"};
    
    public static void main(String[] args) 
    {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } } );
    }
  
    public AdminTrackerGUI()
    {
        AdminTracker.loadDatabases();
        eventArr = AdminTracker.getEvents();
        studentArr = AdminTracker.getStudents();
        
        this.setLayout(new BorderLayout());

        JMenuBar jmb = new JMenuBar();
        JMenu jmbHelp = new JMenu("Help");
        menuAbout = new JMenuItem("About AdminTracker");
        menuHelp = new JMenuItem(new AbstractAction() 
                                     { public void actionPerformed(ActionEvent e) 
                                       { 
                                            JOptionPane.showMessageDialog(((JMenuItem)e.getSource()), "Please see the Batallion Roster Officer.");
                                       } 
                                     } );
        menuHelp.setText("AdminTracker Help");
        menuSave = new JMenuItem(new AbstractAction()
                                      { public void actionPerformed(ActionEvent e) {
                                            JOptionPane.showMessageDialog(((JMenuItem)e.getSource()), "Student library saved successfully? " + LibraryWriter.writeEventLibrary(eventArr));
                                            JOptionPane.showMessageDialog(((JMenuItem)e.getSource()), "Event library saved successfully? " + LibraryWriter.writeStudentLibrary(studentArr));
                                            JOptionPane.showMessageDialog(((JMenuItem)e.getSource()), "Roster library saved successfully? " + LibraryWriter.writeRosterLibrary(eventArr));
                                        }});
        menuSave.setText("Manually Save Libraries");                       
        jmbHelp.add(menuSave);
        jmbHelp.add(menuHelp);
        jmbHelp.add(menuAbout);
        menuSave.addActionListener(this);
        menuAbout.addActionListener(this);
        System.setProperty("apple.laf.useScreenMenuBar", "true");
        jmb.add(jmbHelp);
        add(jmb);
        
        JTabbedPane tabs = new JTabbedPane(); 
        tabs.addTab("Manage Events", eventsTabInit());
        tabs.addTab("Manage Students", studentsTabInit());
        tabs.addTab("Manage Awards", awardsTabInit());
        add(tabs, BorderLayout.SOUTH);
    } 
    
    public void windowDeactivated(WindowEvent e) { }
    public void windowActivated(WindowEvent e) { }
    public void windowDeiconified(WindowEvent e) { }
    public void windowIconified(WindowEvent e) { }
    public void windowClosed(WindowEvent e) { }
    public void windowOpened(WindowEvent e) { }
    
    public void windowClosing(WindowEvent e)
    {
        boolean success = LibraryWriter.writeEventLibrary(eventArr) &&
                          LibraryWriter.writeStudentLibrary(studentArr) &&
                          LibraryWriter.writeRosterLibrary(eventArr);
        String msg = "";
        if(success)
            msg = "AdminTracker has saved the files. Please click OK to close.";
        else
            msg = "ERROR: AdminTracker has FAILED to save the files. Please backup the current copies of your files and contact\n"+
                  "the Battalion Roster Officer. Please press Cancel to return to the program. Java: LibraryWriter error.";
        int choice = JOptionPane.showConfirmDialog(this, msg, "Closing AdminTracker...", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
        if(choice == JOptionPane.OK_OPTION)
        {
            System.exit(0);
        }
    }
    
    public void valueChanged(ListSelectionEvent e)
    {
        if(e.getSource() == studentList && studentList.getSelectedIndex() != -1)
        {
            stuDisplay = studentArr.get(studentList.getSelectedIndex());
            String[] stuData = {stuDisplay.getPlatoon()+"", stuDisplay.getLastName(), stuDisplay.getFirstName(), stuDisplay.getID()+"",
                stuDisplay.getGender(), stuDisplay.getGrade()+"", stuDisplay.getNSYear()+""};
            for(int i = 0; i < studentFields.length; i++)
                studentFields[i].setText(stuData[i]);
                
        }
        else if(e.getSource() == eventList && eventList.getSelectedIndex() != -1)
        {
            evtDisplay = eventArr.get(eventList.getSelectedIndex());
            String[] evtData = {evtDisplay.getName(), evtDisplay.getDateString(), evtDisplay.getCategory().toString(), evtDisplay.getDataName(), evtDisplay.getCountable()+""};
            for(int i = 0; i < eventFields.length; i++)
                if(eventFields[i] != null) eventFields[i].setText(evtData[i]);   
            epm.setSelectedIndex(evtDisplay.getCategory().getIndex());
            boolean isFM = evtDisplay.getCategory().toString().equals("FIELD MEET");
            setEnabledEFMB(isFM);
            if(isFM)
            {
                for(int i = 0; i < eventFMBoxes.length; i++)
                    eventFMBoxes[i].setSelected(((FieldMeet)evtDisplay).getPerformed()[i]);
            }
        }
    }
    
    public void actionPerformed(ActionEvent e)
    {
        if("addStudent".equals(e.getActionCommand()))
        {
            String[] parts = {studentFields[0].getText(), studentFields[1].getText(), studentFields[2].getText(), studentFields[3].getText(), 
                studentFields[4].getText(), studentFields[5].getText(), studentFields[6].getText()};
            if(!studentFields[3].getText().equals(""))
            {
                studentArr.add(0, StudentReader.parseFromString(parts));
                refreshStudents();
            }
        }
        else if("editStudent".equals(e.getActionCommand()) && studentList.getSelectedIndex() != -1)
        {
            String[] parts = {studentFields[0].getText(), studentFields[1].getText(), studentFields[2].getText(), studentFields[3].getText(), 
                studentFields[4].getText(), studentFields[5].getText(), studentFields[6].getText()};
            if(!studentFields[3].getText().equals(""))
            {
                studentArr.set(studentList.getSelectedIndex(), StudentReader.parseFromString(parts));
                refreshStudents();
            }
        }
        else if("removeStudent".equals(e.getActionCommand()) && studentList.getSelectedIndex() != -1)
        {
            int ind = studentList.getSelectedIndex();
            studentArr.remove(ind);
            studentModel.remove(ind);
            refreshStudents();
        }
        else if("pollStudent".equals(e.getActionCommand()) && studentList.getSelectedIndex() != -1)
        {
            JOptionPane.showMessageDialog(this, "Records for " + stuDisplay.getName() +":\n" + AdminTracker.findStudentOnRosters(stuDisplay));   
        }
        else if("addEvent".equals(e.getActionCommand()))
        {
            String[] parts = {eventFields[0].getText(), eventFields[1].getText(), epm.getSelectedItem().toString(), eventFields[3].getText(), eventFields[4].getText(), "1111111"};
            if(!eventFields[0].getText().equals(""))
            {
                Event eventNew = EventReader.parseFromString(parts);
                eventArr.add(eventArr.size(), eventNew);
                refreshEvents();
                updateFMBoxes(eventNew);
            }
            else
            {
                JOptionPane.showMessageDialog(this, "Use the boxes to fill in the information.");
            }
        }
        else if("editEvent".equals(e.getActionCommand()) && eventList.getSelectedIndex() != -1)
        {
            int idx = eventList.getSelectedIndex();
            String[] parts = {eventFields[0].getText(), eventFields[1].getText(), epm.getSelectedItem().toString(), eventFields[3].getText(), eventFields[4].getText(), FMBoxesToString()};
            if(!eventFields[0].getText().equals(""))
            {
                Event eventNew = EventReader.parseFromString(parts);
                eventArr.set(idx, eventNew);
                eventModel.set(idx, eventNew);
                refreshEvents();
                updateFMBoxes(eventNew);
            }
            else
            {
                JOptionPane.showMessageDialog(this, "Use the boxes to fill in the information.");
            }
        }
        else if("removeEvent".equals(e.getActionCommand()) && eventList.getSelectedIndex() != -1)
        {
            int ind = eventList.getSelectedIndex();
            eventArr.remove(ind);
            eventModel.remove(ind);
            refreshEvents();
        }
        else if("displayStudent".equals(e.getActionCommand()) && eventList.getSelectedIndex() != -1)
        {
            Event oldevt = evtDisplay;
            boolean pass = true;
            if(evtDisplay.getCategory().toString().equals("FIELD MEET"))
            {
                efmlist = new JComboBox();
                DefaultComboBoxModel efmm = new DefaultComboBoxModel();
                efmm.addElement("Master Field Meet Roster");
                for(int i = 0; i < fieldMeetLabels.length; i++)
                {
                    if(eventFMBoxes[i].isSelected())
                        efmm.addElement(fieldMeetLongLabels[i]);
                    else
                        efmm.addElement(fieldMeetLongLabels[i] + " (Unavailable)");
                }
                efmlist.setModel(efmm);
                JOptionPane.showMessageDialog(this, efmlist, "Select an event...", JOptionPane.PLAIN_MESSAGE);
                FieldMeet fm = ((FieldMeet)evtDisplay);
                int idx = efmlist.getSelectedIndex();
                if(idx == 0)
                {
                    evtDisplay = ((Event)fm);
                }
                else
                {
                    if(eventFMBoxes[idx-1].isSelected())
                        evtDisplay = fm.getEvent(idx-1);
                    else
                    {
                        pass = false;
                        JOptionPane.showMessageDialog(this, "You selected an event that is unavailable.\n"+
                        "Please select another event, or check the box\nin the main window that corresponds to the event.", "Selection Error", JOptionPane.ERROR_MESSAGE);
                    }
                }
            }
            if(pass)
            {
                displayRosterTable();
                evtDisplay = oldevt;
            }
        }
        else if(e.getSource() == epm)
        {
            if( !((String)epm.getSelectedItem()).endsWith("SERVICE") )
            {
                eventFields[3].setEnabled(false);
                eventFields[4].setEnabled(false);
                eventFields[3].setText("Attendance");
                eventFields[4].setText("1");
            }
            else
            {
                eventFields[3].setEnabled(false);
                eventFields[3].setText("Hours");
                eventFields[4].setEnabled(true);
            }
        }
        else if(e.getActionCommand().equals("Output All Records") || e.getActionCommand().equals("Output All Non-Blank Records"))
        {
            JFileChooser ch = new JFileChooser();
            if(JFileChooser.APPROVE_OPTION == ch.showSaveDialog(this))
            {
                if(!ch.getSelectedFile().exists())
                {
                    try
                    {
                        ch.getSelectedFile().createNewFile();
                    }
                    catch (IOException a)
                    {
                        JOptionPane.showMessageDialog(this, "There is a problem with saving your file.", "Java: IOException", JOptionPane.ERROR_MESSAGE);
                        return;
                    }
                }
                try
                {
                    PrintStream writer = new PrintStream(new FileOutputStream(ch.getSelectedFile()));
                    writer.print("Output of all ");
                    writer.print(e.getActionCommand().contains("Non-Blank")  ? "non-blank " : "");
                    writer.println("records, outputted: " + new Date().toString());
                    writer.println("-------------------------------------------------------------------------");
                    for(int i = 0; i < studentArr.size(); i++)
                    {
                        String studentResult = AdminTracker.findStudentOnRosters(studentArr.get(i));
                        if(!(e.getActionCommand().contains("Non-Blank") && studentResult.equals("No records.")))
                        {
                            writer.println("Records for " + studentArr.get(i).getName() + " ID: " + studentArr.get(i).getID());
                            writer.println(studentResult);
                        }
                    }
                    writer.println("--END OF FILE--");
                    writer.close();
                }
                catch (FileNotFoundException a)
                {
                    JOptionPane.showMessageDialog(this, "There is a problem with saving your file.", "Java: FileNotFoundException", JOptionPane.ERROR_MESSAGE);
                }
            }
        }
        else if(e.getActionCommand().equals("Output Ribbon Awards..."))
        {
            ribbonList = new JComboBox();
            DefaultComboBoxModel ribbonModel = new DefaultComboBoxModel();
            ribbonModel.addElement("ALL RIBBONS");
            //skip the "NONE" and "FIELD MEET" ribbon by starting from 2
            for(int i = 2; i < Category.CATEGORIES.length; i++)
            {
                ribbonModel.addElement(Category.CATEGORIES[i] + " RIBBON");
            }
            ribbonList.setModel(ribbonModel);
            JOptionPane.showMessageDialog(this, ribbonList, "Select a ribbon...", JOptionPane.PLAIN_MESSAGE);
            if(ribbonList.getSelectedIndex() == 0)
                outputAllRibbons();
            else if(ribbonList.getSelectedIndex() > 0)
                outputRibbon(ribbonList.getSelectedIndex()+1, false);
        }
        else if(e.getSource() == menuAbout)
        {
            String aboutAdminTracker = AdminTracker.getAboutAdminTracker();
            JTextArea jta = new JTextArea(aboutAdminTracker, 24, 36);
            jta.setEditable(false);
            jta.setLineWrap(true);
            jta.setWrapStyleWord(true);
            JScrollPane jsp = new JScrollPane(jta, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER );
            JOptionPane.showMessageDialog(this, jsp, "About AdminTracker", JOptionPane.PLAIN_MESSAGE);
        }
    }
    
    public void textValueChanged(TextEvent e)
    {
        if(e.getSource() == tableSearch)
        {
            populateRosterTable(tableSearch.getText().trim().toUpperCase());
        }
    }
    
    //adapted from "How to use JButton etc etc.
    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("AdminTracker");
        frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

        //Create and set up the content pane.
        AdminTrackerGUI newContentPane = new AdminTrackerGUI();
        frame.addWindowListener(newContentPane);
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }
    
    public JPanel eventsTabInit()
    {
        //events tab--------------------------------------------------
        JPanel events = new JPanel();
        
        String[] evts = new String[eventArr.size()];
        for(int i = 0; i < evts.length; i++)
            eventModel.add(i, eventArr.get(i).toString());
        eventList = new JList(eventModel);
        JScrollPane eventsPane = new JScrollPane(eventList);
        eventList.addListSelectionListener(this);
        
        JPanel eventFMOption = new JPanel(new GridLayout(8,1));
        eventFMOption.add(new JLabel("Field Meet Events"));
        eventFMBoxes = new JCheckBox[7];
        for (int i = 0; i < eventFMBoxes.length; i++)
        {
            eventFMBoxes[i] = new JCheckBox(fieldMeetLongLabels[i], true);
            setEnabledEFMB(false);
            eventFMOption.add(eventFMBoxes[i]);
        }
        
        JPanel eventLabelTable = new JPanel(new GridLayout(5,1,0,12));
        JPanel eventInputTable = new JPanel(new GridLayout(5,1));
        eventFields = new JTextField[5];
        String[] lbls = {"Name: ", "Date: ", "Category: ", "Counting: ", "Duration: "}; //adapted from "How to Use SpringLayout"
        for (int i = 0; i < lbls.length; i++) 
        {
            if(i != 2)
            {
                JLabel el = new JLabel(lbls[i], JLabel.TRAILING);
                eventFields[i] = new JTextField(10);
                eventInputTable.add(eventFields[i]);
            }
            else if(i == 2)
            {
                epm = new JComboBox();
                dcbmepm = new DefaultComboBoxModel(); //DefaultComboBoxModelEventPopupMenu
                for(int j = 0; j < Category.CATEGORIES.length; j++)
                {
                    dcbmepm.addElement(Category.CATEGORIES[j]);
                }
                epm.setModel(dcbmepm);
                epm.addActionListener(this);
                epm.setActionCommand("categorySelection");
                eventInputTable.add(epm);
            }
            eventLabelTable.add(new JLabel(lbls[i], JLabel.TRAILING));
        }      
        
        JPanel eventToolsTable = new JPanel();

        JButton[] funEvt = new JButton[3]; //functionEvent
        String[] lblEvt = {"Add", "Edit", "Remove"};
        for(int i = 0; i < funEvt.length; i++)
        {
            funEvt[i] = new JButton(lblEvt[i] + " Event");          
            eventToolsTable.add(funEvt[i]);
            funEvt[i].setActionCommand(lblEvt[i].toLowerCase()+"Event");
            funEvt[i].addActionListener(this);
        }
        
        JButton dspStu;
        dspStu = new JButton("Event Roster");
        eventToolsTable.add(dspStu);
        dspStu.setActionCommand("displayStudent");
        dspStu.addActionListener(this);
        
        //table code went here//
        String[] columnNames = {"Platoon", "Last Name", "First Name", "ID", "Gender", "Grade", "NS Year", "Completed"};     
        Object[][] rowData = new Object[0][columnNames.length];
        tableModel = new AdminTrackerTableModel(rowData, columnNames);
        table = new JTable(tableModel);
        table.setPreferredScrollableViewportSize(new Dimension(600,200));           
        table.doLayout();
        
        scrollPane = new JScrollPane(table);
        
        JPanel upperEvents = new JPanel();
        upperEvents.add(eventsPane);
        upperEvents.add(eventFMOption);
        upperEvents.add(eventLabelTable);
        upperEvents.add(eventInputTable);
        
        JPanel eTop = new JPanel();
        eTop.setLayout(new BorderLayout());
        eTop.add(upperEvents, BorderLayout.NORTH);
        eTop.add(eventToolsTable, BorderLayout.SOUTH);
 
        //events.setLayout(new GridLayout(2,1));
        events.add(eTop);
       // events.add(scrollPane);
        
        return events;
    }
    
    public JPanel studentsTabInit()
    {
        //students tab------------------------------------------------
        JPanel students = new JPanel();
        
        String[] stus = new String[studentArr.size()];
        for(int i = 0; i < stus.length; i++)
            studentModel.add(i, studentArr.get(i).getName());
        studentList = new JList(studentModel);
        JScrollPane studentsPane = new JScrollPane(studentList);
        studentList.addListSelectionListener(this);
        
        JPanel studentInfoTable = new JPanel(new GridLayout(7,2));
        studentFields = new JTextField[7];
        String[] labels = {"Platoon: ", "Last Name: ", "First Name: ", "ID Number: ", "Gender: ", "Grade: ", "NS Year: "}; //adapted from "How to Use SpringLayout"
        int numPairs = labels.length;
        for (int i = 0; i < numPairs; i++) 
        {
            JPanel s = new JPanel();
            JLabel l = new JLabel(labels[i], JLabel.TRAILING);
            studentFields[i] = new JTextField(10);
            l.setLabelFor(studentFields[i]);
            studentInfoTable.add(l);
            studentInfoTable.add(studentFields[i]);
        }

        JButton[] funStu = new JButton[4]; //functionStudent
        String[] lblStu = {"Add", "Edit", "Remove", "Poll"};
        
        JPanel studentToolsTable = new JPanel();
        
        for(int i = 0; i < funStu.length; i++)
        {
            funStu[i] = new JButton(lblStu[i] + " Student");          
            studentToolsTable.add(funStu[i]);
            funStu[i].setActionCommand(lblStu[i].toLowerCase()+"Student");
            funStu[i].addActionListener(this);
        }
        
        JPanel upperStudents = new JPanel();
        upperStudents.setLayout(new BorderLayout());
        upperStudents.add(studentsPane, BorderLayout.WEST);
        upperStudents.add(studentInfoTable, BorderLayout.EAST);
        
        
        students.setLayout(new BorderLayout());
        students.add(upperStudents, BorderLayout.NORTH);
        students.add(studentToolsTable, BorderLayout.SOUTH);
        
        return students;
    }
    
    public JPanel awardsTabInit()
    {
        JPanel awards = new JPanel(new BorderLayout());
        awards.add(new JLabel("An Awards Tab, coming soon to an AdminTracker near you."), BorderLayout.NORTH);
        awards.add(new JButton(new ImageIcon("01.jpg", "Meritorious Achievement")));
        JPanel awardsToolsTable = new JPanel(new GridLayout(2,2));
        JButton[] awardButtonArray = new JButton[4];
        String[] awardButtonLabels = {"Output All Records", "Output All Non-Blank Records", "Output Ribbon Awards...", "Settings..."};
        for(int i = 0; i < awardButtonArray.length; i++)
        {
            awardButtonArray[i] = new JButton(awardButtonLabels[i]);
            awardsToolsTable.add(awardButtonArray[i]);
            awardButtonArray[i].addActionListener(this);
            awardButtonArray[i].setActionCommand(awardButtonLabels[i]);
        }
        awards.add(awardsToolsTable, BorderLayout.SOUTH);
        return awards;
    }
    
    public void refreshEvents()
    {
        Collections.sort(eventArr);
        eventModel.clear();
        for(int i = 0; i < eventArr.size(); i++)
            eventModel.add(i, eventArr.get(i).toString());
        eventList.setModel(eventModel);
    }
    
    public void refreshStudents()
    {
        Collections.sort(studentArr);
        studentModel.clear();
        for(int i = 0; i < studentArr.size(); i++)
            studentModel.add(i, studentArr.get(i).getName());
        studentList.setModel(studentModel);
    }
    
    public Object[] getTableColumnInfo(Event event)
    {
        Object[] result;
        boolean isCountingHours = (event.getCategory().toString().endsWith("SERVICE"));  
        if (event.getParent() == null)
        {
            result = new Object[studentArr.size()]; 
        }
        else
        {
            result = new Object[event.getParent().getTable().size()];
        }         
        Integer idKey = new Integer(0);
        if(isCountingHours)
        {
            for(int i = 0; i < result.length; i++)
            {
                idKey = new Integer(tableModel.getValueAt(i,3).toString());
                result[i] = "";
                if(event.getTable().containsKey(idKey))
                {
                    result[i] = event.getTable().get(idKey).toString();
                }
            }
        }
        else
        {
            for(int i = 0; i < result.length; i++)
            {
                idKey = new Integer(tableModel.getValueAt(i,3).toString());
                result[i] = new Boolean(false);
                if(event.getTable().containsKey(idKey))
                {
                    result[i] = new Boolean(Integer.parseInt(event.getTable().get(idKey).toString()) >= 1);
                }
            }
        }   
        return result;
    }
    
    public void setEnabledEFMB(boolean which)
    {
        for(int i = 0; i < eventFMBoxes.length; i++)
        {
            if(eventFMBoxes[i] != null)
                eventFMBoxes[i].setEnabled(which);
        }
    }
    
    public void displayRosterTable()
    {
        populateRosterTable();
        if(tableModel.getRowCount() == 0)
        {
            JOptionPane.showMessageDialog(this, "According to the master roster, no students\n"+
            "have attended this event. Please check students in the\nmaster roster first before using these ones.", "Selection Error", JOptionPane.ERROR_MESSAGE);
        }
        else
        {
            
            JPanel tablePanel = new JPanel(new BorderLayout());
            tableSearch = new TextField();
            tablePanel.add(tableSearch, BorderLayout.NORTH);
            tablePanel.add(scrollPane, BorderLayout.CENTER);
            tableSearch.addTextListener(this);
            JOptionPane.showMessageDialog(this, /*evtDisplay.getTable().toString()*/ tablePanel, "Roster for " + evtDisplay.toString(), JOptionPane.PLAIN_MESSAGE);
            saveRosterInformation();
        }
    }
    
    public void populateRosterTable()
    {
        populateRosterTable("");
    }
    
    public void populateRosterTable(String match)
    {
        tableModel.setRowCount(0);
        for(int i = 0; i < studentArr.size(); i++)
        {
            if(evtDisplay.getParent() != null)
            {
                if(studentArr.get(i).attended(evtDisplay.getParent()) && studentArr.get(i).getName().indexOf(match) != -1)
                {
                    tableModel.addRow(studentArr.get(i).toStringArray());
                }
            }
            else
            {
                if(studentArr.get(i).getName().indexOf(match) != -1)
                    tableModel.addRow(studentArr.get(i).toStringArray());
            }
        }  
        tableModel.setColumnCount(tableModel.getColumnCount() - 1);
        tableModel.addColumn(evtDisplay.getDataName(), getTableColumnInfo(evtDisplay));
        table.doLayout();
    }
    
    public void saveRosterInformation()
    {
        int dataCol = tableModel.getColumnCount()-1;
        int infoCol = 3; //this has the ID column
        int end = 0;
        if(evtDisplay.getParent() == null)
            end = studentArr.size();
        else
            end = evtDisplay.getParent().getTable().size();
        evtDisplay.getTable().clear();
        if(tableModel.getColumnName(dataCol).equals("Hours"))
        {
            for(int i = 0; i < end; i++)
            {
                if(!tableModel.getValueAt(i, dataCol).toString().equals("") && Integer.parseInt(tableModel.getValueAt(i, dataCol).toString()) > 0)
                {
                    evtDisplay.getTable().put(new Integer(tableModel.getValueAt(i, infoCol).toString()), new Integer(tableModel.getValueAt(i, dataCol).toString()));
                }
            }
        }
        else if(tableModel.getColumnName(tableModel.getColumnCount()-1).equals("Attendance"))
        {
            for(int i = 0; i < end; i++)   
            {
                if(tableModel.getValueAt(i, dataCol).toString().equals("true"))
                {
                    evtDisplay.getTable().put(new Integer(tableModel.getValueAt(i, infoCol).toString()), 1);
                }
            }
        }
    }
    
    public void updateFMBoxes(Event e)
    {
        if(e.getClass().equals(FieldMeet.class))
        {
            FieldMeet fm = ((FieldMeet)e);
            boolean[] pf = new boolean[eventFMBoxes.length];
            for(int i = 0; i < pf.length; i++)
            {
                pf[i] = eventFMBoxes[i].isSelected();
            }
            fm.setPerformed(pf);
        }   
    }
    
    public String FMBoxesToString()
    {
        String result = "";
        if(evtDisplay.getClass().equals(FieldMeet.class))
        {
            for(int i = 0; i < eventFMBoxes.length; i++)
            {
                if(eventFMBoxes[i].isSelected())
                    result = result + "1";
                else
                    result = result + "0";
           }
        }
        return result;
    }
    

    
    public void outputAllRibbons()
    {
        JFileChooser ch = new JFileChooser();
        if(JFileChooser.APPROVE_OPTION == ch.showSaveDialog(this))
        {
            if(!ch.getSelectedFile().exists())
            {
                try
                {
                    ch.getSelectedFile().createNewFile();
                }
                catch (IOException a)
                {
                    JOptionPane.showMessageDialog(this, "There is a problem with saving your file.", "Java: IOException", JOptionPane.ERROR_MESSAGE);
                    return;
                }
            }
            try
            {
                PrintStream writer = new PrintStream(new FileOutputStream(ch.getSelectedFile()));
                writer.print("Output of all ribbons, created " + (new Date()).toString() + ".\n");
                for(int i = 2; i < Category.CATEGORIES.length; i++) //skips the "NONE" and "FIELD MEET" categories
                    writer.println(outputRibbon(i, true));
                writer.println("--END OF FILE--");
                writer.close();
            }
            catch (FileNotFoundException a)
            {
                JOptionPane.showMessageDialog(this, "There is a problem with saving your file.", "Java: FileNotFoundException", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
    
    public String outputRibbon(int categoryIndex, boolean toReturn)
    {
        Category category = new Category(Category.CATEGORIES[categoryIndex]);
        String result = "Output for the " + category.toString() + " RIBBON, created " + (new Date()).toString() + ".\n"+
                        "------------------------------------------------------------\n";
        for(int i = 0; i < studentArr.size(); i++)
        {
            int val = AdminTracker.getAllForStudent(studentArr.get(i), category);
            if(category.toString().equals("PARTICIPATION"))
                val /=3;
            if(category.toString().endsWith("SERVICE"))
                val /=10;
            val = capAward(val, studentArr.get(i)); 
            if(val >= 1)
                result = result + "Student " + studentArr.get(i).getName() + " has earned the " + category.toString() + " " + awardLevel[val] +".\n";
        }
        if(toReturn)
            return result;
        else
        {
            JFileChooser ch = new JFileChooser();
            if(JFileChooser.APPROVE_OPTION == ch.showSaveDialog(this))
            {
                if(!ch.getSelectedFile().exists())
                {
                    try
                    {
                        ch.getSelectedFile().createNewFile();
                    }
                    catch (IOException a)
                    {
                        JOptionPane.showMessageDialog(this, "There is a problem with saving your file.", "Java: IOException", JOptionPane.ERROR_MESSAGE);
                        return "--SAVE ERROR--";
                    }
                }
                try
                {
                    PrintStream writer = new PrintStream(new FileOutputStream(ch.getSelectedFile()));
                    writer.println(result);
                    writer.println("--END OF FILE--");
                    writer.close();
                }
                catch (FileNotFoundException a)
                {
                    JOptionPane.showMessageDialog(this, "There is a problem with saving your file.", "Java: FileNotFoundException", JOptionPane.ERROR_MESSAGE);
                }
            }
        }
        return "";
    }
    
    //precondition: student attended event

    
    public int capAward(int original, Student student)
    {
        int result = original;
        int ns = student.getNSYear();
        boolean secondSem = isSecondSemester();
       
        int cap = ns*2;
        if(!secondSem)
            cap = cap - 1;
        if(result > cap)
            result = cap;
            
        return result;
    }
    
    public boolean isSecondSemester()
    {
        Date now = new Date(), midterm = new Date(), start = new Date();
        try
        {
            now = new Date();     
            SimpleDateFormat sdf = new SimpleDateFormat("MMMddyyyy");
            midterm = sdf.parse("Jan28"+Calendar.getInstance().get(Calendar.YEAR));
            start = sdf.parse("Aug28"+Calendar.getInstance().get(Calendar.YEAR));
        }
        catch(ParseException e)
        {
        }
        return (now.after(midterm) && now.before(start));
    }             
    //end of class :(
}

class AdminTrackerTableModel extends DefaultTableModel
{  
    public AdminTrackerTableModel( Object[][] r, String[] c) { super(r, c); }
    public Class getColumnClass(int col) { return getValueAt(0,col).getClass(); }
    public boolean isCellEditable(int row, int col) { return (col > 6); } 
}          